package com.egao.api.controller;


import cn.hutool.core.util.StrUtil;
import com.egao.api.base.BaseApiController;
import com.egao.common.core.constants.UserConstant;
import com.egao.common.core.utils.StringUtil;
import com.egao.common.core.web.JsonResult;
import com.egao.common.system.entity.OperRecord;
import com.egao.common.system.entity.User;
import com.egao.common.system.service.OperRecordService;
import com.egao.common.system.service.UserService;
import com.egao.orderB.entity.Customer;
import com.egao.orderB.entity.CustomerCopy;
import com.egao.orderB.entity.Driver;
import com.egao.orderB.service.CustomerService;
import com.egao.orderB.service.DriverService;
import io.swagger.annotations.*;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.dao.EmptyResultDataAccessException;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestController;
import org.wf.jwtp.provider.Token;
import org.wf.jwtp.provider.TokenStore;

import javax.servlet.http.HttpServletRequest;

/**
 * api登录相关接口
 * Created by wangfan on 2019-05-29 下午 3:43.
 * http://localhost/swagger-ui.html
 * http://192.168.1.110/swagger-ui.html
 */
@RequestMapping("/api")
@RestController
@Api(value = "登录Api",tags = {"登录Api"})
public class ApiLoginController extends BaseApiController {

//    @Qualifier("jdbcTokenStore")
    @Autowired
    private TokenStore tokenStore;
    @Autowired
    private CustomerService customerService;
    @Autowired
    private DriverService driverService;

    /*@PostMapping("/login2")
    public JsonResult login2(String username, String password, HttpServletRequest request) {
        User user = userService.getByUsername(username);
        if (user == null) return JsonResult.error("账号不存在");
        if (!userService.comparePsw(user.getPassword(), password)) return JsonResult.error("密码错误");
        JsonResult jsonResult = JsonResult.ok("登录成功");
        // 签发token
        Token token = tokenStore.createNewToken(String.valueOf(user.getUserId()), 60 * 60 * 24 * 30L);
        jsonResult.put("access_token", token.getAccessToken());
        return jsonResult;
    }
*/
    /**
     * 登录
     */
    @ApiOperation(value = "用户登录",notes = "返回token,注意保存",httpMethod = "POST")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "username",value = "账号",paramType = "body ",dataType = "String",required = true),
            @ApiImplicitParam(name = "password",value = "密码",paramType = "body ",dataType = "String",required = true)
    })
    @PostMapping("/nt/login")
    @ResponseBody
    public JsonResult login(String username, String password) {
        if (StringUtil.isBlank(username, password)) {
            return JsonResult.error("账号或密码不能为空!");
        }
        User user = null;
        try {
            user = userService.getUserByUsername(new User(username));
            if(user.getDeleted()==1) {
                return JsonResult.error("请等待管理员审核!");
            }
        } catch (EmptyResultDataAccessException e){
            e.printStackTrace();
            return JsonResult.error("没有此用户!");
        } catch (Exception e){
            e.printStackTrace();
            return JsonResult.error("请等待管理员审核!");
        }
        if (user == null) {
            return JsonResult.error("账号不存在!");
        }
        if (user.getState()==2) {
            return JsonResult.error("帐号未审核");
        }
        if (user.getState()!=0) {
            return JsonResult.error("账号被锁定");
        }
        if (!userService.comparePsw(user.getPassword(), password)) {
            return JsonResult.error("密码错误");
        }
        // 签发token
        Token token = tokenStore.createNewToken(String.valueOf(user.getUserId()), new String[]{}, new String[]{}, 60 * 60 * 24 * 30);
        user.setPassword(null);
        Driver driver = new Driver();
        driver.setId(user.getCustomerId()+"");
        if(user.getType().equals("司机")){
            driver = driverService.getById(driver);
        }
        return JsonResult.ok("登录成功").put("access_token", token.getAccessToken()).put("user", user).put("driver", driver);
    }

    /**
     * web注册用户
     */
    @ApiOperation(value = "web端客户(货代)注册",notes = "name 客户名称\n" +
            "socialCode 统一社会信用代码\n" +
            "businessLicense 营业执照图片\n" +
            "username 帐号\n" +
            "password 密码\n" +
            "",httpMethod = "POST")
    @PostMapping("/nt/login/register")
    @ResponseBody
    public JsonResult register(User user, CustomerCopy customer) {
        try{
            return customerService.ApiSave(customer, new User(UserConstant.ADMIN_ID,UserConstant.COMPANY_ID), user);
        } catch (Exception e) {
            return JsonResult.error("注册失败: 用户名已被注册");
        }
    }

    /**
     * 小程序注册用户
     */
    @ApiOperation(value = "小程序端司机注册",notes = "" +
            "username 帐号 必填\n" +
            "password 密码 必填\n" +
            "name 名字 必填\n" +
            "idCard 身份证 必填\n" +
            "carNo 车牌 必填\n" +
            "whiteCard:白卡号\n" +
            "",httpMethod = "POST")
    @PostMapping("/nt/login/wechart/register")
    @ResponseBody
    public JsonResult registerWechart(User user, Driver driver) {
//        try{
//            int userId = userService.apiSave(user);
//            return JsonResult.ok("注册成功!").put("userId",userId);
//        } catch (Exception e) {
//            return JsonResult.error("注册失败: 用户名已被注册!");
//        }
        try{
            return driverService.apiSave(driver, new User(UserConstant.ADMIN_ID,UserConstant.COMPANY_ID), user);
        } catch (Exception e) {
            return JsonResult.error("注册失败: 用户名已被注册");
        }
    }


}
